const {JSON,D,FETCH} = require('../fastfn')
const {check_captcha,decorate_login} = require('../core')
const validate = require('../validate')
const {db,m} = require('../model/m')
const Query = require('../model/Query')
const md5 = require('md5')
const I18N = require('../i18n')
const {randstr} = require('../common')
exports.login = function *(ctx){
    if(ctx.method === 'POST'){
        if(!check_captcha(ctx, ctx.request.body.captcha)) {
            yield JSON({code:1, msg: '验证码错误'})
        }
        let valid = new validate('user')
        let valid_res = valid.scene('login').check(ctx.request.body)
        if(valid_res !== true) {
            yield JSON({code:1, msg: valid_res})
        }
        yield db(async (conn) => {
            try {
                let username = ctx.request.body.username,
                    password = ctx.request.body.password
                let query = new Query(conn, 've_user')
                let res = await query.fields('id,username,password').where('username', username).where('or', 'email', password).find()
                if (res.password === md5(password)) {
                    //登录成功
                    ctx.session.userid = res.id
                    ctx.session.username = res.username
                    return JSON({code: 0, msg: I18N.user.login.success})
                } else {
                    return JSON({code: 1, msg: I18N.user.login.error})
                }
            } catch (err) {
                return JSON({code: 1, msg: I18N.user.login.error})
            }
        })


    }else {
        yield FETCH()
    }

}


exports.register =  function *(ctx) {
    if(ctx.method === 'POST') {
        if(!check_captcha(ctx,ctx.request.body.captcha)) {
            yield JSON({code:1, msg: '验证码错误'})
        }
        //验证激活是否正确
        if(!ctx.request.body.active_code === ctx.session.active_code){
            ctx.session.active_code = undefined
            yield JSON({code:1, msg:'激活码错误'})
        }
        ctx.session.active_code = undefined
        let valid = new validate('user')
        let valid_res = valid.scene('register').check(ctx.request.body)
        if(valid_res !== true) {
            yield JSON({code:1, msg: valid_res})
        }
        yield db(async (conn) => {
            try{
                let username = ctx.request.body.username,
                    password = ctx.request.body.password,
                    email = ctx.request.body.email
                let query = new Query(conn, 've_user')
                let cur = await query.where('username', username).find()
                if(!cur === undefined) {
                    return JSON({code:1,msg:'该用户名已经注册'})
                }
                cur = await query.where('email',email).find()
                if(!cur === undefined) {
                    return JSON({code:1,msg:'该邮箱已经注册'})
                }
                //构建注册用户

                let reg_time = (new Date()).getTime()
                let regForm = {
                    username:username,
                    email:email,
                    password: md5(password),
                    regtime:reg_time
                }
                let res = await query.insert(regForm)
                let lasid = await m(conn, 'select LAST_INSERT_ID() as lastid')
                if(lasid.length > 0) {
                    ctx.session.userid = lasid[0].lastid
                }
                ctx.session.username = username
                return JSON({code:0,msg:'注册成功',redirect:'/user/ucenter'})
            }catch(err) {
                return JSON({code:1,msg:err})
            }
        })
    }else {
        yield FETCH()
    }

}

exports.ucenter = function *(ctx) {
    let islogin = decorate_login(ctx)
    console.log(islogin)
    if(islogin !== true) {
        if(islogin === undefined){
            return
        }
        return JSON(islogin)
    }
    yield D('isLogin',true)
}